package com.clkj.nangang.mvp.index.aboutme;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.clkj.nangang.R;
import com.clkj.nangang.app.CustomApplication;
import com.clkj.nangang.common.Constant;
import com.clkj.nangang.mvp.adapter.NewsListAdapter;
import com.clkj.nangang.mvp.base.BaseFragment;
import com.clkj.nangang.mvp.index.newsdetail.NewsDetailActivity;
import com.clkj.nangang.mvp.model.NewsModel;
import com.clkj.nangang.util.LogUtil;
import com.clkj.nangang.util.XListView;
import com.clkj.nangang.util.schedulers.SchedulerProvider;

import java.util.ArrayList;
import java.util.List;

/**
 * 政策指南中 办事要件，政策解读，服务指南 下的父级资讯类型
 * Created by Administrator on 2017/7/4.
 */

public class FragmentAboutme extends BaseFragment implements AboutMeContract.View, XListView.IXListViewListener {

    //默认的是isFirstVisibles true ,刚进来的时候分两种情况
    //1.如果切过来的时候 setVisibleHint在OnCreate之前调用，那isFirstVisible为true，这个时候不进行任何操作；
    //等方法执行到onActivityCreated的时候，在执行一次setUserVisibleHint 这个时候把默认的是isFirstVisibles 设为false
    //然后这个时候调用setUserVISIBLEhINT为true  去获取数据
    //2.如果是后面再次切过来，那isFirstVisible已经为false，那就可以直接通过setUserVisibleHint获取数据了

    //代表这个界面是不是第一次被使用
    boolean isFirstUsed = true;


    String mNewsType;

    private static final String NEWS_BELONG = "news_belong";
    private XListView lvNews;
    private RelativeLayout noticeEmpty;
    private int page = 1;

    private NewsListAdapter newsListAdapter;
    private List<NewsModel> newsModelList = new ArrayList<>();
    private AboutMeContract.Presenter presenter;

    public static FragmentAboutme newInstance(String newsBelong) {
        Bundle bundle = new Bundle();
        bundle.putSerializable(NEWS_BELONG, newsBelong);

        FragmentAboutme fragment = new FragmentAboutme();
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle bundle = getArguments();
        if (bundle != null) {
            mNewsType = bundle.getString(NEWS_BELONG);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_news, container, false);
        assignView(view);
        initData();
        initView();

        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        //fragment 可见的情况下 进行加载数据。不可见则不加载
        if (getUserVisibleHint() == true) {
            if (isFirstUsed == true) {
                isFirstUsed = false;
                setUserVisibleHint(true);
            }
            //不可见，说明fragment已经初始话完成,就直接把isFirstVisible改为false 再次切过来的时候就直接可以加载数据了
        } else {
            isFirstUsed = false;
        }
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        // LogUtil.e("CartVisible");
        if (getUserVisibleHint()) {
            LogUtil.e("MyShuoShuoVisible");
            //如果不是firstvisible才去进行下面的操作  因为第一次很可能出现各种问题
            if (isFirstUsed == false) {

                presenter.getNewsLists(mNewsType, String.valueOf(page));
            }
        } else {
            LogUtil.e("faXianFragmentVisible");
        }
    }

    @Override
    public void initData() {

        presenter = new AboutMePresenter(this, SchedulerProvider.getInstance(), CustomApplication.getInstance().getHttpService());
    }

    @Override
    public void assignView(View view) {

        lvNews = (XListView) view.findViewById(R.id.lv_news);
        noticeEmpty = (RelativeLayout) view.findViewById(R.id.notice_empty);

    }

    @Override
    public void initView() {

        lvNews.setPullLoadEnable(true);
        lvNews.setPullRefreshEnable(true);
        lvNews.setXListViewListener(this);

        newsListAdapter = new NewsListAdapter(CustomApplication.globeContext, newsModelList);
        lvNews.setAdapter(newsListAdapter);

        lvNews.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                String newsId = newsModelList.get(position - 1).getID();

                Intent it = new Intent(getActivity(), NewsDetailActivity.class);
                it.putExtra("newsId", newsId);
                startActivity(it);

            }
        });
    }

    @Override
    public void onNetError(String tip) {
        Toast.makeText(CustomApplication.globeContext, tip, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void getNewsListsSuccess(List<NewsModel> newsModels) {

        lvNews.setVisibility(View.VISIBLE);
        if (page == 1) {
            newsModelList.clear();
        }
        if (newsModels.size() > 0) {
            if (newsModels.size() < Constant.DEFAULT_PAGE_SIZE) {
                Toast.makeText(CustomApplication.globeContext, "数据已经全部加载", Toast.LENGTH_SHORT).show();
                lvNews.setPullLoadEnable(false);
            } else {
                lvNews.setPullLoadEnable(true);
            }
            newsModelList.addAll(newsModels);
        } else {
            lvNews.setPullLoadEnable(false);
            if (newsModelList.size() == 0) {
                lvNews.setEmptyView(noticeEmpty);
            } else {
                Toast.makeText(CustomApplication.globeContext, "数据已经全部加载", Toast.LENGTH_SHORT).show();
            }
        }
        //停止刷新或加载
        onStopLoad();

        newsListAdapter.notifyDataSetChanged();
    }

    @Override
    public void getNewsListsFail(String tip) {
        Toast.makeText(CustomApplication.globeContext, tip, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void setPresenter(AboutMeContract.Presenter presenter) {
        this.presenter = presenter;
    }

    //刷新加载
    @Override
    public void onRefresh() {

        page = 1;
        presenter.getNewsLists(mNewsType, String.valueOf(page));
    }

    @Override
    public void onLoadMore() {
        page++;
        presenter.getNewsLists(mNewsType, String.valueOf(page));
    }

    private void onStopLoad() {
        lvNews.stopRefresh();
        lvNews.stopLoadMore();
    }
}

